#include "Renderer_PCH.h"
#include "BindFramebufferEvent.h"

/*--------------------------------------------------------------------------*/

BindFramebufferEvent::BindFramebufferEvent(const std::string& fbo, const std::string& clear) :
	m_framebuffer(NULL),
	m_clearflags(0),
	m_isBackbuffer(false)
{
	if (fbo == "BACKBUFFER")
	{
		m_isBackbuffer = true;
	}
	else
	{
		m_framebuffer = g_Renderer->GetRendererStorageMgr()->GetFramebuffer(fbo);
	}
	
	if (strstr(clear.c_str(), "color"))
	{
		m_clearflags |= GL_COLOR_BUFFER_BIT;
	}

	if (strstr(clear.c_str(), "stencil"))
	{
		m_clearflags |= GL_STENCIL_BUFFER_BIT;
	}

	if (strstr(clear.c_str(), "depth"))
	{
		m_clearflags |= GL_DEPTH_BUFFER_BIT;
	}
}

/*--------------------------------------------------------------------------*/

BindFramebufferEvent::~BindFramebufferEvent()
{

}

/*--------------------------------------------------------------------------*/

bool BindFramebufferEvent::CallEvent()
{
	if (m_framebuffer)
	{
		m_framebuffer->Bind();
		glViewport(0, 0, m_framebuffer->GetWidth(), m_framebuffer->GetHeight());

		GLenum clratt[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3}; 

		for (uint i = 0; i < RFRAMEBUFFER_MAX_COLORS; ++i)
		{
			if (m_framebuffer->GetColor(i) == NULL)
			{
				clratt[i] = GL_NONE;
			}
		}

		glDrawBuffers(4, clratt);
	}
	else if (m_isBackbuffer)
	{
		RFramebuffer::Unbind();
		glViewport(0, 0, g_Renderer->GetResX(), g_Renderer->GetResY());
	}
	else
	{
		__Check(false);
	}
	
	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
	glStencilMask(0xff);
	glDepthMask(GL_TRUE);

	glClear(m_clearflags);

	return true;
}

/*--------------------------------------------------------------------------*/
